//
//  showImageViewController.swift
//  weibo1
//
//  Created by 李进 on 15/10/28.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit
import SVProgressHUD

let showImageCellId = "showImageCellId"

class showImageViewController: UIViewController {
    
    //声明两个属性来接收传递进来的数据
   private var urls:[NSURL]
    
   private var currentIndexPath: NSIndexPath
    
    //实现构造函数
    init(urls:[NSURL], indexpath:NSIndexPath){
        
        self.urls = urls
        
        self.currentIndexPath = indexpath
        
        super.init(nibName: nil, bundle: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
/// 这个方法就像 storyboand 一样override
    override func loadView() {
        super.loadView()
        
        //为了使得根每个cell 之间都能有一个间隙来设置更视图的大小
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
        setupUI()
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.blackColor()
        
    }
    
    //实现构造方法
    
    //MARK: 自定义流水布局－嵌套flowlayout类
    class showImageViewFlowLayout:UICollectionViewFlowLayout{
        
        //实现构造方法
        override func prepareLayout() {
            super.prepareLayout()
            itemSize = collectionView!.bounds.size
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsVerticalScrollIndicator = false
            
        }
    }
    
    //懒加载所需要的
    //关闭按钮
    private lazy var closeBut:UIButton = UIButton(tittle: "关闭", backImageName: nil, fontsize: 15, fontcolcr: UIColor.lightGrayColor())
    //保存按钮
    private lazy var saveBut:UIButton = UIButton(tittle: "保存", backImageName: nil, fontsize: 15, fontcolcr: UIColor.lightGrayColor())
    //scrollview
    private lazy var collscrollView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: showImageViewFlowLayout())
    //图片显示视图
    private lazy var imageview:UIImageView = UIImageView()
}

// MARK: - 设置UI
extension showImageViewController{
    
    private func setupUI(){
        
        //添加控件
        view.addSubview(collscrollView)
        view.addSubview(closeBut)
        view.addSubview(saveBut)
        
        
        //设置自动布局
        collscrollView.frame = view.bounds
        
        closeBut.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveBut.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        //设置按钮的监听方法
        closeBut.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBut.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        //准备控件
        prepareCollectionview()
        
    }
    //实现监听按钮的监听方法
    @objc private func close(){
        
       // print("关闭按钮点击")
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    //保存按钮的垫肩事件
    @objc private func save(){
        
       // print("保存按钮的点击")
        // 1. 拿到图片
        let cell = collscrollView.visibleCells()[0] as! ShowImageCVCell
        // imageView 中很可能会因为网络问题没有图片 -> 下载需要提示
        guard let image = cell.imageView.image else {
            return
        }
        
        // 2. 保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        
        let message = error != nil ? "保存失败" : "保存成功"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    //这边实准备控件，
    private func prepareCollectionview() {
        
        //注册cell
        collscrollView.registerClass(ShowImageCVCell.self, forCellWithReuseIdentifier: showImageCellId)
        
        collscrollView.dataSource = self
    }
    
}

// MARK: - UICollectionViewDataSource的数据源方法
extension showImageViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(showImageCellId, forIndexPath: indexPath) as! ShowImageCVCell
        cell.imageURL = urls[indexPath.item]
        
        return cell
    }
    
}

extension showImageViewController: PhotoBrowserCellDelegate{
    
    func photoBrowserCellDidTapImage() {
        close()
    }
    
}